import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, Spin, message} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, PAGE} from '../constants';
import WrappedSelect from '../common/WrappedSelect';
import {PERMISSION} from './constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import {validateAdd} from './utils';
const FormItem = Form.Item;
const autosize = {minRows: 1};
const EMPTY_ARRAY = [];
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    onSubmit = () => {
        const result = validateAdd(this.props.conditions, this.props.id);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    render() {
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.title',
                                defaultMessage: '银行信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.brandId ? 'error' : null}
                                        required={!this.props.id}>
                                        {this.props.id ? <span className="value-font">{`(${this.props.conditions.brandCode})${this.props.conditions.brandName}`}</span>
                                            : <WrappedSelect
                                                name="brandId"
                                                value={this.props.conditions.brandId}
                                                options={this.props.brands}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.code ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.code',
                                            defaultMessage: '编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id ? <span className="value-font">{this.props.conditions.code}</span>
                                            : <TextInput name="code"
                                                value={this.props.conditions.code} onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.name ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.name',
                                            defaultMessage: '银行名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="name"
                                            value={this.props.conditions.name} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.engName ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.engName',
                                            defaultMessage: '英文名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="engName"
                                            value={this.props.conditions.engName} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.account ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.account',
                                            defaultMessage: '银行账号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="account"
                                            value={this.props.conditions.account} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.accountCode ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.accountCode',
                                            defaultMessage: '银行识别码'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="accountCode"
                                            value={this.props.conditions.accountCode} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.companyName ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.companyName',
                                            defaultMessage: '公司名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="companyName"
                                            value={this.props.conditions.companyName} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.address',
                                        defaultMessage: '地址'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="address" autosize={autosize}
                                        value={this.props.conditions.address} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}>
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onSubmit,
    getDetail,
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);

const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: item.name,
            value: item.id
        }));
    }
);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
    brands: getBrandsData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => {
        if(ownProps.id)
            return dispatch(getDetail(ownProps.id));
        return null;
    },
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onSubmit(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
